package com.chenjt.juc.five_interrupt;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * 注释：
 *
 * @author chenjt
 * @date 2024/7/8 9:40
 */
public class InterruptDemo {


    static volatile boolean isStop = false;
    static AtomicBoolean atomicBoolean = new AtomicBoolean(false);

    public static void main(String[] args) {

//        m1_volatitle();
//        m2_AtomicBoolean();

        m3_interrupt_api();

    }

    /**
     * Thread类自带的中断api实例方法实现中断运行中的线程
     */
    private static void m3_interrupt_api() {

        Thread t1 = new Thread(() -> {
            while(true){
                // 判断当前线程是否被中断
                if(Thread.currentThread().isInterrupted()){
                    System.out.println(Thread.currentThread().getName() + "\t isInterrupted()被修改为true，程序停止");
                    break;
                }
                System.out.println("t1 ----hello interrupt api");
            }
        }, "t1");
        t1.start();


        // false
        System.out.println("-------t1的默认中断标志位：" + t1.isInterrupted());

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }


        // 其他线程叫我中断
        new Thread(()->{
            // 设置线程的中断状态为true，发起一个协商而不会立刻停止线程
            t1.interrupt();
        },"t2").start();
        // 自己把自己中断
//        t1.interrupt();


    }

    /**
     * 通过AtomicBoolean变量实现停止中断运行中的程序
     */
    private static void m2_AtomicBoolean() {

        new Thread(()->{
            while(true){
                if(atomicBoolean.get()){
                    System.out.println(Thread.currentThread().getName() + "\t atomicBoolean被修改为true，程序停止");
                    break;
                }
                System.out.println("t1 ----hello atomicBoolean");
            }
        },"t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            atomicBoolean.set(true);
        },"t2").start();

    }


    /**
     * 通过volatile变量实现停止中断运行中的线程
     */
    private static void m1_volatitle() {

        new Thread(()->{
            while(true){
                if(isStop){
                    System.out.println(Thread.currentThread().getName() + "\t isStop被修改为true，程序停止");
                    break;
                }
                System.out.println("t1 ----hello volatile");
            }
        },"t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        new Thread(()->{
            isStop = true;
        },"t2").start();

    }


}
